package org.zxp.thread.tools;

import java.util.concurrent.Exchanger;

/**
 * @program: zxp-thread-test
 * @description:  Exchanger进行测试
 * @author: X-Pacific zhang
 * @create: 2019-05-25 15:44
 **/
public class ExchangerTest {
    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            String message = "No.1";
            System.out.println(Thread.currentThread().getName()+"处理中");
            try {
                String exchange = exchanger.exchange(message);
                System.out.println(Thread.currentThread().getName()+"获得交换变量："+exchange);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程1").start();

        Thread.sleep(1000);
        new Thread(() -> {
            String message = "No.2";
            System.out.println(Thread.currentThread().getName()+"处理中");
            try {
                String exchange = exchanger.exchange(message);
                System.out.println(Thread.currentThread().getName()+"获得交换变量："+exchange);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程2").start();
    }
}
